{include file="public/layout" /}
<body class="laytp-container">
<div class="layui-card" id="search-form">
  <div class="layui-card-body">
      <form class="layui-form layui-row layui-col-space16 layui-search-admin">
        <div class="layui-inline">
          <label class="layui-form-label">商品名称</label>
          <div class="layui-input-inline">
            <input type="text" name="name" placeholder="商品名称" lay-affix="clear" class="layui-input">
          </div>
        </div>

        <div class="layui-inline">
          <label class="layui-form-label">供货商ID</label>
          <div class="layui-input-inline">
            <input type="text" name="sid" placeholder="供货商ID" lay-affix="clear" class="layui-input">
          </div>
          <a href="javascript:vodi(0)" class="layui-btn layui-btn-primary" onclick="chooseBusinessShow()">查找商户ID</a>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">添加时间</label>
          <div class="layui-inline" id="laydate-rangeLinked">
            <div class="layui-input-inline">
              <input type="text" name="time_start" autocomplete="off" id="table-search-date-start" class="layui-input" placeholder="开始日期">
            </div>-
            <div class="layui-input-inline">
              <input type="text" name="time_end" autocomplete="off" id="table-search-date-end" class="layui-input" placeholder="结束日期">
            </div>
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label"></label>
          <button class="layui-btn" lay-submit lay-filter="demo-table-search">搜索</button>
          <button type="reset" class="layui-btn layui-btn-primary">清空</button>
        </div>
      </form>
  </div>
</div>
<div class="layui-card">
  <div class="layui-card-body">
    <table class="layui-hide" id="goods" lay-filter="test"></table>
  </div>
</div>
<div id="auditLayer" style="margin-top:80px;margin-right:20px;display: none">
    <div class="layui-form">
	<div class="layui-form-item" >
		<label class="layui-form-label" style="width:80px">状态</label>
		<div class="layui-input-inline" style="width:350px">
			<input type="radio" name="status" value="1" title="通过" checked="checked"/>
			<input type="radio" name="status" value="2" title="拒绝" />
		</div>
	</div>
	<div class="layui-form-item" style="margin-top:40px;margin-right:20px;">
		<label class="layui-form-label" style="width:80px">审核备注</label>
		<div class="layui-input-inline" style="width:200px">
			<input type="text" id="tuireason" class="layui-input"/>
		</div>
	</div>
    </div>
</div>
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" onclick="add()">
      添加
    </button>
    <button class="layui-btn layui-btn-sm" onclick="reload()">
      刷新数据
    </button>
    <button class="layui-btn layui-btn-sm" onclick="del()">
      批量删除
    </button>
    <button class="layui-btn layui-btn-sm" data-form-export="{:url('excel')}">
      导出数据
    </button>

  </div>
</script>
<script type="text/html" id="barDemo">
  <div class="layui-clear-space">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<!--    <a class="layui-btn layui-btn-xs" lay-event="more">-->
<!--      更多-->
<!--      <i class="layui-icon layui-icon-down"></i>-->
<!--    </a>-->
  </div>
</script>
<script>
  var tableIns
  var datawhere
  layui.use(function(){
    var table = layui.table;
    var dropdown = layui.dropdown;
    var laydate = layui.laydate;
    var form = layui.form;

    // 创建渲染实例
    tableIns = table.render({
      elem: '#goods',
      url:'{:url("index")}', // 此处为静态模拟数据，实际使用时需换成真实接口
      toolbar: '#toolbarDemo',
      defaultToolbar: ['filter', 'exports', 'print', {
        title: '提示',
        layEvent: 'LAYTABLE_TIPS',
        icon: 'layui-icon-tips'
      }],
      height: 'full-200', // 最大高度减去其他容器已占有的高度差
      css: [ // 重设当前表格样式
        '.layui-table-tool-temp{padding-right: 145px;}'
      ].join(''),
      cellMinWidth: 80,
      totalRow: false, // 开启合计行
      page: true,
      pagebar: '#test-pagebar', // 分页栏模板
      cols: [[
        {type: 'checkbox', fixed: 'left'},
        {field:'goods_id', fixed: 'left', width:80, title: 'ID', sort: true},
        {field:'supply_name', fixed: 'left', width:80, title: '供货商', sort: true},
        {field:'leixing', width:150, title: '商品类型',totalRowText: ''},
        {field:'goods_name', width:150, title: '商品名称',totalRowText: ''},
        {field: 'original_img', title: '缩略图',templet:function(d){
          var html = '<img src="'+d.original_img+'" width="50" height="50"  onclick="showBigImage(this)" />';
          return html;
        }},
        {field:'market_price', width:80, title: '原价',totalRowText: ''},
        {field:'shop_price', width:80, title: '销售价',totalRowText: ''},
        {field:'cost_price', width:80, title: '成本价',totalRowText: ''},
        // {field:'pv', width:80, title: 'PV',totalRowText: ''},
        {field:'sales_sum', width:80, title: '销量',totalRowText: '',edit:'text'},
        {field:'sort', width:80, title: '排序',totalRowText: '',edit:'text'},
        {field:'is_on_sale', width:80, title: '上架状态',templet:function (d) {
            if(d.is_on_sale){
               return '<span onclick="changeStatus('+d.goods_id+')" style="color: green;cursor:pointer ">上架</span>';
            }else{
               return '<span onclick="changeStatus('+d.goods_id+')" style="color: red;cursor:pointer">下架</span>';
            }
          }},
        {field:'status', width:150, title: '审核状态',templet:function (d) {
            if(d.status==1){
              return '<span style="color: green;cursor:pointer ">审核通过</span>';
            }else if(d.status==2){
              return '<span style="color: red;cursor:pointer">审核拒绝('+d.reason+')</span>';
            }else{
              return  '<span>待审核</span>';
            }
          }},

        {field:'on_time', title:'上架时间'},
        // {field: 'reg_time', title: '注册时间',sort: true,templet:function(d){ return date('Y-m-d H:i',d.reg_time)}},

        {fixed: 'right', title:'操作', width: 150, minWidth: 150,  templet:function(d){
          var html = '';
            html += '<a class="layui-btn layui-btn-xs" onclick="edit(' + d.goods_id + ')">编辑</a>';
        {if $sid==0}
          if(d.status==0) {
            html += '<a class="layui-btn layui-btn-xs" onclick="audit(' + d.goods_id + ')">审核</a>';
          }
        {/if}
      return html;
    }}
      ]],
      error: function(res, msg){
        console.log(res, msg)
      }
    });

    // 触发单元格工具事件
    table.on('tool(test)', function(obj){ // 双击 toolDouble
      var data = obj.data; // 获得当前行数据
      // console.log(obj)
      if(obj.event === 'edit'){
        layer.open({
          title: '编辑 - id:'+ data.goods_id,
          type: 2,
          shadeClose: true,
          area: ['100%','100%'],
          scrollbar:false,
          content: '/admin/Goods/edit/id/'+data.goods_id
        });
      } else if(obj.event === 'more'){
        // 更多 - 下拉菜单
        dropdown.render({
          elem: this, // 触发事件的 DOM 对象
          show: true, // 外部事件触发即显示
          data: [{
            title: '查看',
            id: 'edit'
          },{
            title: '删除',
            id: 'del'
          }],
          click: function(menudata){
            if(menudata.id === 'edit'){
              layer.msg('查看操作，当前行 ID:'+ data.goods_id);
            } else if(menudata.id === 'del'){
              layer.confirm('真的删除行 [id: '+ data.goods_id +'] 吗？', function(index){
                $.ajax({
                  type: "POST",
                  url: "{:url('delete')}",
                  data: {goods_ids: data.goods_id},
                  success: function(res){
                    console.log(res);
                    if(res.status){
                      obj.del(); // 删除对应行（tr）的DOM结构
                      layer.close(index);
                    }else{
                      layer.msg(res.msg);
                    }
                    setTimeout(function(){
                      parent.layer.closeAll();
                      parent.tableIns.reload()
                    },1000)
                  }
                });

                // 向服务端发送删除指令
              });
            }
          },
          align: 'right', // 右对齐弹出
          style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
        })
      }
    });
    table.on('edit(test)', function(obj){
      var field = obj.field; // 得到修改的字段
      var value = obj.value // 得到修改后的值
      var oldValue = obj.oldValue // 得到修改前的值 -- v2.8.0 新增
      var data = obj.data // 得到所在行所有键值
      var col = obj.getCol(); // 得到当前列的表头配置属性 -- v2.8.0 新增
      console.log(obj); // 查看对象所有成员

      $.ajax({
        type: "POST",
        url: "{:url('edit_field')}",
        data: {field_key: obj.field,field_value:obj.value,goods_id:obj.data.goods_id},
        success: function(res){
          console.log(res);
          if(res.status){
            layer.msg(res.msg);
            setTimeout(function(){
              tableIns.reload('test', {
                where: datawhere,
              }, true);
            },1000)
          }else{
            layer.msg(res.msg);
          }
        }
      });

      // 更新当前缓存数据
      var update = {};
      update[field] = value;
      obj.update(update, true); // 参数 true 为 v2.7 新增功能，即同步更新其他包含自定义模板并可能存在关联的列视图
    });
    laydate.render({
      elem: '.demo-table-search-date'
    });
    // 搜索提交
    form.on('submit(demo-table-search)', function(data){
      var field = data.field; // 获得表单字段
      datawhere = field;
      // 执行搜索重载
      table.reload('goods', {
        page: {
          curr: 1 // 重新从第 1 页开始
        },
        where: field // 搜索的字段
      });
      //layer.msg('搜索成功<br>此处为静态模拟数据，实际使用时换成真实接口即可');
      return false; // 阻止默认 form 跳转
    });
  });
  function add(){
    layer.open({
      title: '添加',
      type: 2,
      shadeClose: true,
      area: ['100%','100%'],
      scrollbar:false,
      content: '{:url("edit")}'
    });
  }
  function reload(){
    layui.table.reload('goods', {
      // where: {
      //   abc: 123,
      //   test: '新的 test1'
      // },
      // scrollPos: 'fixed',  // 保持滚动条位置不变 - v2.7.3 新增
      // height: 2000, // 测试无效参数（即与数据无关的参数设置无效，此处以 height 设置无效为例）
      //url: '404',
      //page: {curr: 1, limit: 30} // 重新指向分页
    }, true);
  }
  function del(){
      var checkStatus = layui.table.checkStatus('goods');
      var data = checkStatus.data;
      var goods_ids = [];
      $.each(data, function(index, value){
        //goods_ids.append(value.goods_id);
        goods_ids.push(value.goods_id);
      });
      console.log(goods_ids);
    layer.confirm('确定要删除选择的数据' + goods_ids + '吗？', function (index) {
      $.ajax({
        type: "POST",
        url: "{:url('delete')}",
        data: {goods_ids: goods_ids},
        success: function(res){
          console.log(res);
          if(res.status){
            layer.msg(res.msg);
            setTimeout(function(){
              tableIns.reload('test', {
                where: datawhere,
              }, true);
            },1000)
          }else{
            layer.msg(res.msg);
          }
        }
      });
    });
    //layer.alert(layui.util.escape(JSON.stringify(goods_ids)));
  }
  function changeStatus(goods_id){
    layer.confirm('改变产品ID' + goods_id + '的上架状态吗？', function (index) {
      $.ajax({
        type: "POST",
        url: "{:url('changeStatus')}",
        data: {goods_id: goods_id},
        success: function(res){
          console.log(res);
          if(res.status){
            layer.msg(res.msg);
            setTimeout(function(){
              tableIns.reload('test', {
                where: datawhere,
              }, true);
            },1000)
          }else{
            layer.msg(res.msg);
          }
        }
      });
    });
  }
  function chooseBusinessShow(){
    layer.open({type:2,title:'选择会员',content:"{:url('Suppliers/choosesupply',['args'=>'promoter'])}",area:['900px','600px'],shadeClose:true});
  }
  function choosebusiness(data){
    console.log(data);
    $('input[name="sid"]').val(data.id)
  }
  function edit(goods_id){
    layer.open({
      title: '编辑 - id:'+ goods_id,
      type: 2,
      shadeClose: true,
      area: ['100%','100%'],
      scrollbar:false,
      content: '/admin/Goods/edit/id/'+goods_id
    });
  }
  function audit(id){
    var refundLayer = layer.open({type:1,area:['500px','250px'],title:false,content:$('#auditLayer'),shadeClose:true,btn: ['确定', '取消'],
      yes:function(){
        var index = layer.load();
        $.post("{:url('audit')}",{goods_id:id,reason:$('#tuireason').val(),status:$('input[name="status"]:checked').val()},function(res){
          layer.close(index);
          dialog(res.msg,res.status);
          layer.close(refundLayer);
          tableIns.reload()
        })
      }
    })
  }
</script>
</body>
</html>